const xss = require('xss')
const { exec } = require('../db/mysql')

const getList = async (userId) => { 
    let sql = `select a.id,a.user_id AS userId, date_format(a.createtime, '%Y-%m-%d %H:%i:%s') AS createtime,a.valid,d.id AS doctorId,d.truename,d.hospname,d.deptname,d.positional,d.doctorphoto,d.description from appointments a left join doctors d  on a.doctor_id = d.id where  a.user_id = ${userId} order by a.createtime desc;` 
    return await exec(sql)
}

const getDetail = async (id) => {
    const sql = `select * from blogs where id='${id}'`
    const rows = await exec(sql)
    return rows[0]
}

const newAppointment = async (appointmentData = {}) => { 
    const userId = xss(appointmentData.userId) 
    const doctorId = xss(appointmentData.doctorId)  

    const sql = `insert into appointments (user_id, createtime,doctor_id,valid)
        values ('${userId}', now(), '${doctorId}',0);`

    const insertData = await exec(sql)
    return {
        id: insertData.insertId
    }
} 

const countAppointment = async (appointmentData = {}) => { 
	const userId = xss(appointmentData.userId)
	const doctorId = xss(appointmentData.doctorId) 
    const sql = `select count(*) AS count  from appointments where valid = 0 and user_id='${userId}' and doctor_id='${doctorId}';`  
	const rows = await exec(sql)
	return rows[0].count
}

const totalAppointment = async (appointmentData = {}) => { 
	const userId = xss(appointmentData.userId) 
    const sql = `select count(*) AS count  from appointments where valid = 0 and user_id='${userId}';`  
	const rows = await exec(sql)
	return rows[0].count
}
module.exports = {
    getList,
    getDetail,
    newAppointment,
    countAppointment,
	totalAppointment
}